﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Utils;
using System.IO;
using System.Text;

namespace ICSharpCode.CodeCompletion
{
    /// <summary>
    /// Extensions methods for TextEditor
    /// </summary>
    public static class TextEditorExtensions
    {
        /// <summary>
        /// Loads a file into TextEditor, reads the options included in the file and assigns the code to the avalonedit.
        /// </summary>
        /// <param name="editor"></param>
        /// <param name="fileName">The file</param>
        public static void LoadWithOptions(this TextEditor editor, string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = FileReader.OpenStream(fs, editor.Encoding ?? Encoding.UTF8))
                {
                    //the first line is the options, we don't want to show it
                    reader.ReadLine();

                    StringBuilder code = new StringBuilder();
                    while (!reader.EndOfStream)
                    {
                        code.AppendLine(reader.ReadLine());
                    }

                    editor.Text = code.ToString();
                    editor.Encoding = reader.CurrentEncoding; // assign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
                }
                editor.IsModified = false;
            }
        }
    }
}
